package general;

import in.Daemon;

import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

import out.Sender;

import storage.Storage;
import config.Configurator;

/** Главный класс контроля и запуска
 * 
 * @author Last G
 *
 */
public class Main
{
	private static Logger logger;
	private static in.Daemon in;
	private static out.Sender out;
	private static storage.Storage storage;
	private static Map<String, Map<String, String>> configs;
	/**
	 * Message queue for main class
	 */
	public static final ConcurrentLinkedQueue<Message> Messages = new ConcurrentLinkedQueue<Message>();

	/**
	 * Главный класс
	 * 
	 * @param args
	 *            командная строка
	 */
	public static void main(String[] args)
	{
		try
		{
			configs = Configurator.getCongigurations();
			logger = new Logger(configs);
		} catch (Exception e)
		{
			System.err
					.println("The big problem have been occured and we have to crash");
			System.err.println(e.getLocalizedMessage());
			e.printStackTrace(System.err);
			System.exit(1);
		}
		try
		{
			logger.info("Server is starting");
			storage = new Storage(configs);
			logger.info("Storage created");
			in = new Daemon(configs);
			logger.info("Daemon created");
			in.start();
			logger.info("Daemon started");
			out = new Sender(configs);
			logger.info("Sender created");
			out.start();
			logger.info("Sender started");

			monitor();
		}
		catch (Exception e) 
		{
			logger.error("Server stopped cause smth bad occured: " + e.getMessage());
			System.err.println("The big problem have been occured and we have to crash");
			System.err.println(e.getLocalizedMessage());
			e.printStackTrace(System.err);
			System.exit(1);
		}
	}

	private static void monitor()
	{
		while (true)
		{
			if (Messages.isEmpty())
			{
				try
				{
					Thread.sleep(400);
				} catch (InterruptedException e)
				{
					logger.warn("Main thread has been iterrupted");
				}
			} else
			{
				proceedMessage();
			}
		}
	}

	private static void proceedMessage()
	{
		while (!Messages.isEmpty())
		{
			Message msg = Messages.poll();
		}

	}

	/**
	 * @return the logger object
	 */
	public static Logger getLogger()
	{
		return logger;
	}

	/**
	 * @return storage 
	 */
	public static storage.Storage getStorage()
	{
		return Main.storage;
	}
}
